package com.ruoyi.mobile.utils.baiduT;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaiduTranslator {
    private static final String APP_ID = "20240527002062590";
    private static final String SECRET_KEY = "syW6801LMnOSFh96h2I8";

    public static String translate(String query, String from, String to) throws Exception {
        TransApi api = TransApi.getInstance(APP_ID, SECRET_KEY);
        String result = api.getTransResult(query, from, to);
        System.out.println(result);
        JSONObject jsonObject = new JSONObject(result);
        System.out.println(jsonObject);
        JSONArray ary = (JSONArray)jsonObject.get("trans_result");
        JSONObject aryObj = (JSONObject)ary.get(0);
        String dst = aryObj.getStr("dst");
        return dst;
    }

    public static String unicodeToCN(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

}
